#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能童话书 - 核心应用模块
"""

import os
import sys
import json
import logging
from datetime import datetime
from flask import Flask, render_template, request, jsonify, session
from flask_cors import CORS
import secrets

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入智能故事引擎
from intelligent_story_engine import IntelligentStoryEngine, EmotionType

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/app_enhanced.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# 创建Flask应用
app = Flask(__name__)
app.secret_key = secrets.token_hex(16)
CORS(app)

# 全局变量
story_engine = None
app_stats = {
    "total_stories": 0,
    "user_sessions": 0,
    "average_rating": 0.0,
    "start_time": datetime.now()
}

def initialize_enhanced_app():
    """初始化增强版应用"""
    global story_engine
    
    try:
        os.makedirs('logs', exist_ok=True)
        os.makedirs('static/images', exist_ok=True)
        os.makedirs('templates', exist_ok=True)
        
        logger.info("正在初始化智能故事生成引擎...")
        story_engine = IntelligentStoryEngine()
        logger.info("✅ 智能故事引擎初始化完成！")
        
        return True
        
    except Exception as e:
        logger.error(f"❌ 应用初始化失败: {e}")
        return False

@app.route('/')
def enhanced_index():
    """增强版主页"""
    try:
        if 'user_id' not in session:
            session['user_id'] = secrets.token_hex(8)
            app_stats["user_sessions"] += 1
        
        return render_template('index_enhanced.html', 
                             stats=app_stats,
                             emotions=[e.value for e in EmotionType])
    except Exception as e:
        logger.error(f"主页加载失败: {e}")
        return f"应用加载失败: {e}", 500

if __name__ == '__main__':
    print("🎭 智能童话书增强版")
    print("🚀 正在启动...")
    
    if initialize_enhanced_app():
        print("✅ 初始化成功！")
        print("🌐 访问地址: http://localhost:5001")
        app.run(host='0.0.0.0', port=5001, debug=True)
    else:
        print("❌ 初始化失败！")